package 单例模式;

/**
 * @program: leetcode
 * @description: 懒汉式：虽然达到了按需初始化的目的，但是却也带来了不安全的问题
 * @author: HuRan QQ1345122890
 * @create: 2022-02-07 10:56
 */
public class Mgr05 {
    //volatile 防止指令重排序
    private volatile static Mgr05 INSTANCE;

    private Mgr05() {
    }

    public static Mgr05 getInstance() {
        if (INSTANCE == null) {
            //此方法不能保证多线程情况下是安全的
            synchronized (Mgr05.class) {
                //双重检查
                if (INSTANCE == null) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    INSTANCE = new Mgr05();
                }

            }
        }
        return INSTANCE;
    }

    public void m() {
        System.out.println("m");
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                System.out.println(Mgr05.getInstance().hashCode());
            }).start();
        }
    }
}